#pragma once
#include <memory>
#include <iostream>
#include "async_session.h"
#include "sigc++/sigc++.h"
#include "asio.hpp"

class AsyncServer {
public:
    AsyncServer(asio::io_context& io, uint16_t port)
        : io_(io)
          , acceptor_(io, asio::ip::tcp::endpoint(asio::ip::tcp::v4(), port))
          //, acceptor_(io, asio::ip::tcp::endpoint(asio::ip::make_address("127.0.0.1"), port)) 
    {
	    port_ = port;
    }

    sigc::signal<void(std::shared_ptr<AsyncSession>)> signal_new_connection;

    void start() {
	    do_accept(); 
    }

private:
    void do_accept() {
        acceptor_.async_accept([this](std::error_code ec, asio::ip::tcp::socket socket) {
			std::cout << "in server async_accept, ec is  " <<  ec << std::endl;
            if (!ec) {
                auto session = std::make_shared<AsyncSession>(std::move(socket));
                signal_new_connection.emit(session);
                session->start();
            }
            do_accept();
        });
    }

    asio::io_context& io_;
    asio::ip::tcp::acceptor acceptor_;
    uint16_t port_;
};

